package cn.tjad.tjad2.data.session;

import com.qiandian.android.base.common.bean.CommonBean;

import java.util.ArrayList;
import java.util.List;

import cn.tjad.tjad2.data.bean.User;
import cn.tjad.tjad2.net.http.ResponseObserver;
import cn.tjad.tjad2.net.http.RetrofitManager;
import cn.tjad.tjad2.utils.RxUtils;
import cn.tjad.tjad2.utils.Tools;

public class ProjectUsers {

    private volatile static ProjectUsers instance;
    private int projectId;
    private List<User> projectUsers;

    private ProjectUsers() {}

    public static ProjectUsers getInstance() {
        if (instance == null) {
            synchronized (ProjectUsers.class) {
                if (instance == null) {
                    instance = new ProjectUsers();
                }
            }
        }
        return instance;
    }

    public void getProjectUsers(OnProjectUserListener listener) {
        if (Tools.getProjectId() == projectId) {
            if (projectUsers != null) {
                notifyCaller(listener, projectUsers);
            } else {
                requestProjectUsers(listener);
            }
        } else {
            requestProjectUsers(listener);
        }
    }

    private void requestProjectUsers(OnProjectUserListener listener) {
        RetrofitManager.getInstance()
                .getApiService()
                .getUsers(Tools.getProjectId())
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<ArrayList<User>>(null) {
                    @Override
                    public void onSuccess(CommonBean<ArrayList<User>> t) {
                        projectId = Tools.getProjectId();
                        projectUsers = t.result;
                        notifyCaller(listener, projectUsers);
                    }

                    @Override
                    public void onFailed(String message) {

                    }
                });
    }

    private void notifyCaller(OnProjectUserListener listener, List<User> projectUsers) {
        if (listener != null) {
            listener.onProjectUserGet(projectUsers);
        }
    }

    public interface OnProjectUserListener {
        void onProjectUserGet(List<User> userList);
    }
}
